﻿<template>
    <div class="container" style="width:99%;margin-top:-25px;">
	<!-- 查询条件 -->
    <div class="query-box">
        <el-form :model="queryBox" status-icon ref="queryBox">
          <el-row>
            <el-col :span="4">
               <div class="depart-box">
                <div class="slect-title">客户类型</div>
                <el-select clearable v-model="queryBox.customerType" filterable>
                  <el-option
                    v-for="item in student_type_options"
                    :key="item.key"
                    :label="item.value"
                    :value="item.key"
                  ></el-option>
                </el-select>
                </div>
            </el-col>
            <el-col :span="4">
               <div class="depart-box">
                  <div class="slect-title">客户来源</div>
                   <el-select filterable clearable v-model="queryBox.customerSource" placeholder="请选择" >
                      <el-option
                      v-for="item in student_data_from_options"
                      :key="item.key"
                      :label="item.value"
                      :value="item.key">
                      {{item.value}}
                      </el-option>
                  </el-select>
                </div>
            </el-col>
            <el-col :span="4">
              <div class="depart-box">
                  <div class="slect-title">客户进展</div>
                  <el-form-item @change="student_progress_change">
                    <el-select clearable v-model="queryBox.customerProgress" placeholder="请选择">
                        <el-option
                        v-for="item in student_progress_options"
                        :key="item.value"
                        :label="item.value"
                        :value="item.key">
                        {{item.value}}
                        </el-option>
                    </el-select>
                  </el-form-item>
                </div>
            </el-col>
            <el-col :span="4">
               <el-form-item label="" prop="customerNumber">
                <el-input v-model="queryBox.customerNumber" placeholder="客户编号">
                    <template slot="prepend">客户编号</template>
                </el-input>
              </el-form-item>
            </el-col>
             <el-col :span="4">
                <el-form-item label="" prop="agentName">
                <el-input v-model="queryBox.agentName" placeholder="意向客户">
                    <template slot="prepend">意向客户</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="4">
              <div class="depart-box">
                <div class="slect-title">历史跟进人</div>
                <el-autocomplete
                  v-model="assigner"
                  :fetch-suggestions="querySearchAsync2"
                  placeholder="请输入内容"
                  clearable
                  @select="handleSelect2"
                  :change="handleClearable()"
                ></el-autocomplete>
              </div>
            </el-col>
             <el-col :span='7'>
               <div class="depart-box">
                  <div class="slect-title">创建时间</div>
                   <el-date-picker
                      v-model="createDate"
                      type="daterange"
                      :start-placeholder="'开始时间'"
                      :end-placeholder="'结束时间'"
                      range-separator="至"
                      :default-time="['00:00:00', '23:59:59']"
                       value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss">
                    </el-date-picker>
                </div>
            </el-col>
             <el-col :span='7'>
               <div class="depart-box">
                  <div class="slect-title" style="width: 150px;">最新跟进时间</div>
                   <el-date-picker
                      v-model="trackingDate"
                      type="daterange"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      :default-time="['00:00:00', '23:59:59']" 
                      value-format="yyyy-MM-dd HH:mm:ss" 
                      format="yyyy-MM-dd HH:mm:ss">
                    </el-date-picker>
                </div>
            </el-col>
            
          </el-row>
          <el-row style="margin-top:1%;">
             <el-col :span="4">
                <el-form-item label="" prop="phone">
                <el-input v-model="queryBox.phone" placeholder="请输入电话">
                    <template slot="prepend">联系电话</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-row class="area">
                <el-col :span="6" style="margin-left:0;">
                  <span class="city-title">所在地区：</span>
                </el-col>
                <el-col :span="14" style="margin-left:-1px">
                  <el-form-item label prop="area">
                    <el-cascader
                      clearable
                      size="large"
                      :options="options"
                      v-model="selectedOptions"
                    ></el-cascader>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </el-form>
        <div class="from-btns">
            <kt-button :label="$t('action.reset')" perms="true" type="primary" @click="reset('queryBox')"/>
            <kt-button :label="$t('action.search')" perms="true" type="primary" @click="search"/>
        </div>
    </div>
     <div class="add-btns fl">
      <kt-button
        :label="$t('action.batchdistribution')"
        :disabled="this.selections.length===0"
        perms="customerSea:xuecoo:batchdistribution"
        type="primary"
        @click="handlebatchdistribution"
      />
    </div>
	<!--表格内容栏-->
	<Crm-table   class="table-width" xuecooCustomerSea width="400"
    permsReceive="customerSea:xuecoo:Receive" :loading="loading"
		:data="pageResult" :columns="columns" @handleReceive='handleReceive'
    @handleSee="handleSee"
    @selectionChange="selectionChange"
    @handleCoutomersort="handleCoutomersort"
		@findPage="findPage">
	</Crm-table >

  <!--批量分配-->
  <div class="batchdistribution-pop">
    <el-dialog
      :visible.sync="batchdistribution"
      @close="$emit('update:batchdistribution', false)"
      width="30%"
    >
      <el-row>
        <el-col :span="24"  style="margin:10px 0 20px 0;">
          <span class="batchdistribution-pop-tit">客户分配</span>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24" style="margin-bottom: 20px;">
          <span class="checked-person">已经选择{{selections.length}}位客户</span>
        </el-col>
      </el-row>
      <el-form :inline="true" :model="addstuformData" class="demo-form-inline">
        <el-row>
          <el-row>
            <el-col :span="6">
              <span class="tit">划分方式：</span>
            </el-col>
            <el-col :span="18">
              <el-select
                clearable
                v-model="deptmodeoptionsValue"
                placeholder="请选择"
                @change="deptmodeoptionsChange"
              >
                <el-option
                  v-for="item in deptmodeoptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-col>
          </el-row>
        </el-row>
        <el-row style="margin-top:5%"  v-if="isShowFlag==1||isShowFlag==2">
          <el-col :span="24">
            <el-row>
              <el-col :span="6">
                <span class="tit">选择部门：</span>
              </el-col>
              <el-col :span="18">
                <popup-tree-input
                  :data="deptData3"
                  :props="deptTree"
                  :prop="deptinputValue"
                  :currentChangeHandle="handleTreeSelectChange3Add"
                ></popup-tree-input>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
        <el-row style="margin-top:5%"  v-if="isShowFlag==2">
          <el-col :span="24">
            <el-row>
              <el-col :span="6">
                <span class="tit">人员选择：</span>
              </el-col>
              <el-col :span="18">
                <el-select
                  clearable
                  v-model="deptuseroptionValue"
                  placeholder="请选择"
                  @change="deptuserchange"
                >
                  <el-option
                    v-for="item in deptuseroption"
                    :key="item.id"
                    :label="item.realName"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="batchdistribution = false">取 消</el-button>
        <el-button type="primary" v-if="isShowFlag==1" @click="batchdistributionsubmitdept">确 定</el-button>
        <el-button type="primary" v-if="isShowFlag==2" @click="batchdistributionsubmituser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
  </div>
</template>
<script>
import PopupTreeInput from "@/components/PopupTreeInput";
import KtButton from "@/views/Core/KtButton";
import CrmTable from "@/views/Core/CrmTable";
import CrmSwitch from "@/views/Core/CrmSwitch";
import { CodeToText } from "element-china-area-data";
import { baseUrl } from '@/utils/global'
import { regionDataPlus } from 'element-china-area-data'
import Cookies from "js-cookie";
import axios from "axios";
export default {
  name: "Xuecoo",
  components: {
    PopupTreeInput,
    CrmTable,
    KtButton,
    CrmSwitch
  },
  data() {
    return {
      aa: true,
      checkedPeson: 0,
      isShowFlag: 0, //0:初始化部门、人员不显示  1:部门显示 2：人员显示
      size: "small",
      // filters: {
      //   name: ""
      // },
      // 查询条件
      student_data_from_options: [
        {
          label: " ",
          key: " "
        }
      ],
      student_type_options:[],
      student_progress_options: [
        {
          label: " ",
          key: " "
        }
      ],
      student_data_from_type_options: [
        {
          label: " ",
          key: " "
        }
      ],
      width: 200,
      columns: [
        { type: "index", label: "序号", minWidth: 50 },
        { prop: "agentName", label: "意向客户", minWidth: 180 },
        { prop: "contactPhone", label: "联系电话", minWidth: 120 },
        { prop: "diqu", label: "地区", minWidth: 190 },
        { prop: "customerSource", label: "客户来源", minWidth: 100 },
        { prop: "customerType", label: "客户类型", minWidth: 120 },
        { prop: "customerProgress", label: "客户进展", minWidth: 70 },
        { prop: "lastBelongPeople", label: "历史跟进人", minWidth: 100 },
        // { prop: "contacts", label: "联系人", minWidth:100 },
        { prop: "createDate", label: "创建时间", minWidth: 180 },
        { prop: "trackingDate", label: "最新跟进时间", minWidth: 180 },
        // { prop: "customerNumber", label: "客户编号", minWidth: 180 }
      ],
      pageRequest: { pageNum: 1, pageSize: 10 },
      pageResult: {
        content: []
      },
      student_type_options:[],
      operation: true, // true:新增, false:编辑
      batchdistribution: false, //显示批量分配弹窗
      customerownership: false, //显示客户归属弹窗
      selectionsLength: "",
      deptTreeProps: {
        label: "name",
        children: "children"
      },
      roles: [],
      selections: [], //选中列表集合
      ids: [], //分配ID集合
      ids2: [],
      deptData: [], //部门树
      deptData2: [], //学酷部门树
      deptData3: [], //总部门树
      deptTree: {
        label: "deptName",
        children: "children"
      },
      deptinputValue: "",
      // 划分方式
      deptmodeoptions: [
        {
          label: "分配至部门",
          value: "11"
        },
        {
          label: "分配至个人",
          value: "9"
        }
      ],
      deptmodeoptionsValue: "",
      submitID: "",
      deptId: "",
      userID: "", //人员ID
      deptuseroption: [], //部门用户
      deptuseroptionValue: "",
      branchcenter: [], //分中心下拉
      branchcenterValue: "",
      branchcenterValueID: "",
      branchcenterCodeValue: "", //分中心编码
      addstuformData: {},
      student_type_options:[],
      trackingDate:'',
      createDate: "",
      loading: false, // 加载标识
      //   地区
      options: regionDataPlus,
      selectedOptions: [],
      queryBox: {
        belongType:'4',
        customerSource: "",
        customerProgress: "",
        customerType:''
      },
      assigner:''
    };
  },
  methods: {
    // 搜索
    search() {
      this.loading = true;
      this.queryBox.province=this.selectedOptions[0]
      this.queryBox.city=this.selectedOptions[1]
      this.queryBox.area=this.selectedOptions[2]
      this.queryBox.createStartDate=this.createDate[0]
      this.queryBox.createStopDate=this.createDate[1]
      this.queryBox.trackingStartDate=this.trackingDate[0]
      this.queryBox.trackingStopDate=this.trackingDate[1]
      this.pageRequest.pageNum = 1;
      this.findPage(null)
    },
    // 获取分页数据
    findPage: function(data) {
      if (data !== null) {
        this.loading = true;
        this.pageRequest = data.pageRequest;
        this.pageRequest=Object.assign({},this.pageRequest,{belongType:'4'})
      }
      this.queryBox.pageSize = this.pageRequest.pageSize;
      this.queryBox.pageNum = this.pageRequest.pageNum;
      this.$api.agent
        .customerSeas(this.queryBox)
        .then(res => {
          let content = {'content':res.investmentInfos,'totalSize':res.total};
          this.pageResult=content;
          this.pageResult.content.forEach(item => {
           if(item.province==null&&item.city==null||item.province=='null'&&item.city=='null'){
              item.diqu=""
            }else{
                item.diqu = (CodeToText[item.province]==undefined?'':CodeToText[item.province]) +
                (CodeToText[item.city]==undefined?'':CodeToText[item.city]) +
                (CodeToText[item.area]==undefined?'':CodeToText[item.area]);
                  // item.diqu = CodeToText[item.province] + CodeToText[item.city]+ CodeToText[item.area];
            }
            this.student_data_from_options.forEach(type_item=>{
              if(type_item.key==item.dataFrom){
                item.laiyuan=type_item.value
              }
            })
            this.student_progress_options.forEach(progress_item=>{
              if(progress_item.key==item.progress){
                item.getprogress=progress_item.value
              }
            })
            // 获取方式对应
            this.student_data_from_type_options.forEach(data_from_type_item=>{
              if(data_from_type_item.key==item.progress){
                item.getType=data_from_type_item.value
              }
            })
            // 客户类型对应
            this.student_type_options.forEach(student_type_item=>{
              if(student_type_item.key==item.type){
                item.type=student_type_item.value
              }
            })
          });
          this.loading = false
        })
        .then(data != null ? data.callback : "");
    },
    // 加载用户角色信息
    // findUserRoles: function() {
    //   this.$api.role.findAll().then(res => {
    //     // 加载角色集合
    //     this.roles = res.data;
    //   });
    // },
    // 重置
    reset(queryBox) {
     this.$refs.queryBox.resetFields();
      this.queryBox.customerType = "";
      this.queryBox.customerSource = "";
      this.queryBox.customerProgress = "";
      this.queryBox.customerNumber=''
      this.queryBox.agentName=''
      this.createDate=[]
      this.queryBox.createStartDate=''
      this.queryBox.createStopDate=''
      this.trackingDate=''
      this.queryBox.trackingStopDate =''
      this.queryBox.trackingStartDate = "";
      this.selectedOptions=[]
      this.pageRequest.pageNum = 1;
      this.assigner = "";
      this.queryBox.lastBelongPeople=""
      this.queryBox.belongTo = "";
      this.findPage(null);
    },
    // 领取
    handleReceive(params){
      this.$api.agent
        .getInternationalWatersCus({
          customerId: params.row.id,
          // belongType: 9,
          // belongTo:localStorage.getItem('userId')
        }).then(res=>{
          if(res.result==2){
            this.$message({
              message: res.msg,
              type: 'error'
            })
            
          }else if(res.result==1){
             this.$message({
              message: res.msg,
              type: 'success'
            })
            this.findPage(null)
          }
          
        })
    }, 
    // 查看客户档案
    handleSee: function(params) {
      this.dataForm = Object.assign({}, params.row);
      // console.log(params.row)
      this.$router.push({
        path: "/Customerfile/XuecooAgent",
        query: {
          id: this.dataForm.id
        }
      });
    },
     // 获取来源
    get_student_data_from() {
      this.student_data_from_options=JSON.parse(localStorage.getItem('investmentSource'))
    },
    get_student_progress() {
      this.student_progress_options=JSON.parse(localStorage.getItem('investmentProgress'))
    },
    student_progress_change(value) {
      this.queryBox.student_progressValue = value.toString();
    },  
    get_student_type() {
      this.student_type_options=JSON.parse(localStorage.getItem('investmentType'))
    },
    get_student_data_from_type(){
      this.student_data_from_type_options=JSON.parse(localStorage.getItem('investmentDataFromType'))
    },
    student_parent_type_change(value) {
      this.info.studentInfoDetail.studentInfoAttr.parentType = value.toString();
    },

    selectionChange: function(params) {
      let selectionsLength = params.selections.length;
      this.selections = selections.selections;
    },
    // 获取选中的表格数据
    selectionChange: function(selections) {
      this.selections = selections.selections;
    },

    // 批量分配
    handlebatchdistribution(params) {
      this.batchdistribution = true;
      this.ids = [];
      let idstu = this.selections.map(item => item.id);
      // this.dataFormAdd = Object.assign({}, params.row);
      this.ids = idstu;
      this.deptmodeoptionsValue = "";
      this.deptinputValue = "";
      this.deptuseroptionValue = "";
      this.isShowFlag=0
    },
    // 批量分配提交分配到部门
    batchdistributionsubmitdept() {
      let customerIds = this.ids.join(",");
      this.$api.agent
        .investmentAllotCustomer({
          customerIds: customerIds,
          belongType: 2,
          threeDeptId: this.deptId //部门ID
        })
        .then(res => {
          if (res.result === 1) {
            this.$message({
              message: res.msg,
              type: "success"
            });
            this.batchdistribution = false;
            this.findPage(null);
          } else {
            this.batchdistribution = false;
            this.$message({
              message: res.msg,
              type: "error"
            });
          }
        });
    },
    // 分配给个人
    batchdistributionsubmituser() {
      let customerIds = this.ids.join(",");
      this.$api.agent
        .investmentAllotCustomer({
          customerIds: customerIds,
          belongType: 1,
          threeDeptId: this.deptId, //部门ID
          assigner: this.userID
        })
        .then(res => {
          if (res.result === 1) {
            this.$message({
              message: res.msg,
              type: "success"
            });
            this.batchdistribution = false;
            this.findPage(null);
          } else {
            this.batchdistribution = false;
            this.$message({
              message: res.msg,
              type: "error"
            });
          }
        });
    },

     // 获取部门数据
    get_dept_data() {
      //deptType:1 部门类型 1 学生 2 学酷 3 网校 4 学校
      // this.$api.dropdown.deptLevel3({deptType:2}).then(res => {
      //   this.tableData = res.departmentInfoList;
      //   this.deptData = res.departmentInfoList;
      //   this.date = res.departmentInfoList;
      //   this.date.forEach(item => {
      //     item.text = item.deptName;
      //     item.value = item.deptName;
      //   });
      // });
      this.deptData=JSON.parse(localStorage.getItem('deptLevel3Chinaedu'))
       this.deptData2=JSON.parse(localStorage.getItem('deptLevel3Xuecoo'))
       this.deptData3=[...this.deptData,...this.deptData2]
    },
    // 点击部门
    handleTreeSelectChange3Add(data, node) {
      this.deptinputValue = data.deptName;
      this.deptId = data.id;
      this.deptuseroptionValue=''
      this.get_dept_user();
    },
    //划分方式 控制部门人员显示
    deptmodeoptionsChange(value) {
      if (value == 9) {
        this.isShowFlag = 2;
      } else if (value == 11) {
        this.isShowFlag = 1;
      } else {
        this.isShowFlag = 0;
      }
    },
    // 获取部门用户
    get_dept_user() {
      this.$api.dropdown
        .users({ userType: 3, threeLevelDeptId: this.deptId,accountStatus:1,isControlResource: 1})
        .then(res => {
          this.deptuseroption = res.userInfoList;
        });
    },
    deptuserchange(value) {
      this.userID = value;
    },

    // 销售人员远程搜索
    querySearchAsync2(queryString, callback) {
      let restaurants = [{}];
      let results = "";
      let threeId=JSON.parse(Cookies.get("threeLevelDeptId"))
      if(threeId==null){
        this.$api.dropdown.users({ userType: 3,deptType:2}).then(res => {
          for (let i of res.userInfoList) {
            i.value = i.realName; //将想要展示的数据作为value
          }
          restaurants = res.userInfoList;
          results = queryString
            ? restaurants.filter(this.createFilter2(queryString))
            : restaurants;
          callback(results);
        });
      }else{
        this.$api.dropdown.users({ userType: 3,deptType:2,threeLevelDeptId:this.deptId}).then(res => {
          for (let i of res.userInfoList) {
            i.value = i.realName; //将想要展示的数据作为value
          }
          restaurants = res.userInfoList;
          results = queryString
            ? restaurants.filter(this.createFilter2(queryString))
            : restaurants;
          callback(results);
        });
      }
    },
    createFilter2(queryString) {
      return restaurant => {
        return (
          restaurant.realName
            .toLowerCase()
            .indexOf(queryString.toLowerCase()) === 0
        );
      };
    },
    handleSelect2(item) {
      this.queryBox.lastBelongPeople = item.id;
    },
    handleClearable(value){
      if(this.assigner==''){
        this.queryBox.lastBelongPeople = ''
      }
    },
    // 资源互转
    handleCoutomersort(params){
       this.$api.agent
        .updateCoutomersort({
          coustomerId:params.row.id,
          customerSort:4 //3 学酷  4 网校
        })
        .then(res => {
          if(res.result==1){
             this.$message({
              message: res.msg,
              type: "success"
            });
            this.findPage(null)
          }else{
            this.$message({
              message: res.msg,
              type: "error"
            });
          }
        })
    }
  },
  mounted() {
    this.get_dept_data()
    this.get_student_data_from();
    this.get_student_progress();
    this.get_student_type()
    this.get_student_data_from_type()
  }
};
</script>
<style >
@import url("../../assets/queryBox.css");
</style>
<style lang='scss' scoped>
.checked-person {
  margin-top: -10%;
}
.batchdistribution-pop-tit{
  font-size: 20px;
  font-weight: bold;
  display: inline-block;
  color: #303133;
}
.demo-form-inline{
  width: 90%;
  margin: 0 auto;
  .el-dialog__body .el-input{
    width: 93% !important;
  }
  .el-select{
    width: 100% !important;
  }
  .tit{
    display: inline-block;
    margin-top: 10%;
  }
}
.el-dialog__body{
  overflow: hidden;
}
</style>

<style lang='scss'>
.batchdistribution-pop .el-dialog__header{
  padding: 0 0 0 0 !important;
}
</style>


